<?php
/* This code is based on Project Babel
*  Original Author: Livid Torvalds
*  Rework:Fujiwara Sai
*/

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

/* S Geo class */
function is_valid_geo($child) {
	$sysfiles = array('.', '..', '.svn', 'data.xml', 'map.xml', '.DS_Store');
	if (in_array($child, $sysfiles)) {
		return false;
	} else {
		return true;
	}
}

function calc_geo_break($avg) {
	switch ($avg) {
		case 2:
		default:
			$br = 12;
			break;
		case 3:
			$br = 10;
			break;
		case 4;
			$br = 8;
			break;
		case 5:
			$br = 6;
			break;
		case 6:
			$br = 4;
			break;
	}
	return $br;
}

class Geo {
	public $map;
	public $path;
	public $geo;
	
	public function __construct($geo, $map_loaded = false) {
		if ($map_loaded) {
			$this->map = $map_loaded;
		} else {
			$xml = simplexml_load_file(DISCUZ_ROOT . 'forumdata/geo/map.xml');
			$this->map = array();
			
			$this->map['path'] = array();
			foreach ($xml->xpath('//location') as $node) {
				$this->map['path'][strval($node->geo)] = strval($node->at) . strval($node->geo);
			}
			
			$this->map['name'] = array();
			foreach ($xml->xpath('//location') as $node) {
				$this->map['name'][strval($node->geo)] = strval($node->cn);
			}
			
			$xml = null;
		}
		$this->geo = new stdClass();
		$this->geo->geo = $geo;
		if (array_key_exists($geo, $this->map['path'])) {
			$this->geo->at = $this->map['path'][$geo];
		} else {
			$this->geo->geo = false;
		}
		if ($this->geo->geo != false) {
			$this->geo->xml = $this->nmRead($geo);
			$this->geo->name = new stdClass();
			$this->geo->name->cn = strval($this->geo->xml->name->cn);
			$this->geo->name->en = strval($this->geo->xml->name->en);
			$this->geo->description = new stdClass();
			$this->geo->description->cn = strval($this->geo->xml->description->cn);
			if (isset($this->geo->xml->description->via)) {
				$this->geo->description->via = strval($this->geo->xml->description->via);
			} else {
				$this->geo->description->via = '';
			}
		}
	}
	
	public function __destruct() {
	}
	
	public function nmRead($geo) {
		$xml = simplexml_load_file(DISCUZ_ROOT . 'forumdata/geo' . $this->map['path'][$geo] . '/data.xml');
		return $xml;
	}
	
	public function nmIsExist($geo = '') {
		if ($geo == '') {
			return false;
		} else {
			if (array_key_exists($geo, $this->map['name'])) {
				return true;
			} else {
				return false;
			}
		}
	}
	
	public static function nmAddUsageSimple($Geo, $db) {
		$_t = time();
		$sql = "UPDATE {$tablepre}geo_usage_simple SET gus_hits = gus_hits + 1, gus_lastupdated = {$_t} WHERE gus_geo = '{$Geo->geo}'";
		mysql_query($sql, $db);
		if (mysql_affected_rows($db) == 1) {
			return true;
		} else {
			$Geo->name->cn_real = mysql_real_escape_string($Geo->name->cn, $db);
			$Geo->name->en_real = mysql_real_escape_string($Geo->name->en, $db);
			$sql = "INSERT INTO {$tablepre}geo_usage_simple(gus_geo, gus_name_cn, gus_name_en, gus_hits, gus_lastupdated) VALUES('{$Geo->geo}', '{$Geo->name->cn_real}', '{$Geo->name->en_real}', 1, $_t)";
			mysql_query($sql, $db);
			if (mysql_affected_rows($db) == 1) {
				return true;
			} else {
				return false;
			}
		}
	}
	
	public function nmGetParallelArray($geo = '') {
		if ($geo == '') {
			$geo = $this->geo->geo;
		}
		$_path = substr($this->map['path'][$geo], 0, strlen($this->map['path'][$geo]) - strlen($geo));
		$A = array();
		$_base = DISCUZ_ROOT . 'forumdata/geo' . $_path;
		$dh = opendir($_base);
		while (($_geo = readdir($dh)) !== false) {
			if (is_valid_geo($_geo)) {
				if ($geo != $_geo) {
					$A[$_geo] = iconv('utf-8', 'gbk', $this->map['name'][$_geo]);
				//	$A[$_geo] = $this->map['name'][$_geo];
				}
			}
		}
		closedir($dh);
		ksort($A);
		return $A;
	}
	
	public function nmGetChildrenArray($geo = '') {
		if ($geo == '') {
			$geo = $this->geo->geo;
		}
		$_path = $this->map['path'][$geo];
		$A = array();
		$_base = DISCUZ_ROOT . 'forumdata/geo' . $_path;
		$dh = opendir($_base);
		while (($_geo = readdir($dh)) !== false) {
			if (is_valid_geo($_geo)) {
				$A[$_geo] = iconv('utf-8', 'gbk', $this->map['name'][$_geo]);
				//$A[$_geo] = $this->map['name'][$_geo];
			}
		}
		closedir($dh);
		ksort($A);
		return $A;
	}
	
	public function nmGetRecursiveChildrenArray($geo = '', $sql = false) {
		if ($geo == '') {
			$geo = $this->geo->geo;
		}
		$A = array();
		$prefix = $this->map['path'][$geo];
		$prefix_length = mb_strlen($prefix, 'UTF-8');
		foreach ($this->map['path'] as $g => $p) {
			if (mb_substr($p, 0, $prefix_length) == $prefix && $g != $geo) {
				if ($sql) {
					$A[] = "'" . mysql_real_escape_string($g) . "'";
				} else {
					$A[$g] = $this->map['name'][$g];
				}
			}
		}
		if ($sql) {
			$A[] = "'" . mysql_real_escape_string($geo) . "'";
		}
		ksort($A);
		return $A;
	}
	
	public function nmGetParentObject($geo = '') {
		if ($geo == '') {
			$geo = $this->geo->geo;
		}
		$_path = $this->map['path'][$geo];
		$_path_a = explode('/', $_path);
		if (count($_path_a) == 2) {
			return false;
		} else {
			$_o = new stdClass();
			$_o->geo = $_path_a[count($_path_a) - 2];
			$_o->name = new stdClass();
			$_o->name->cn = $this->map['name'][$_o->geo];
			return $_o;
		}
	}
	
	public function ShowRoute() {
		$geo_route = $this->nmGetRoute();
		$i = 0;
		foreach ($geo_route as $g => $g_name) {
			$i++;
			if ($i == 1) {
				if ($g == $geo) {
					echo($g_name);
				} else {
					echo('<a href="/bbs/geo/' . $g . '" class="o">' . $g_name . '</a>');
				}
			} else {
				if ($g == $geo) {
					echo(' &gt; ' . $g_name);
				} else {
					echo(' &gt; <a href="/bbs/geo/' . $g . '" class="o">' . $g_name . '</a>');
				}
			}
		}
	}
	
	public function Show_Child_Route(){
		$geos_children = $this->nmGetChildrenArray($geo);
		if (count($geos_children) > 0) {
			$len_total = 0;
			foreach ($geos_children as $elem) {
				$len_total = $len_total + mb_strlen($elem, 'UTF-8');
				//$len_total = iconv('utf-8', 'gbk', $len_total);
			}
			$len_avg = floor($len_total / count($geos_children));
			$br = calc_geo_break($len_avg);
 				$o = '';
				$o .= '<div class="geo_home_content">';
				$o .= '<blockquote>';
				$i = 0;
				foreach ($geos_children as $g => $g_name) {
					$i++;
					$css_color = rand_color();
					$o .= '<a href="/bbs/geo/' . $g . '" class="var" style="color: ' . $css_color . ';">' . $g_name . '</a>&nbsp; ';
					if ($i % $br == 0) {
						$o .= '<br />';
					}
				}
				$o .= '</blockquote>';
				$o .= '</div>';
				echo $o;
			
		}
	}
	
	public function Show_Parallel_Route(){
		$geos_parallel = $this->nmGetParallelArray($geo);
		if (count($geos_parallel) > 0) {
			$len_total = 0;
			foreach ($geos_parallel as $elem) {
				$len_total = $len_total + mb_strlen($elem, 'UTF-8');
				//$len_total = iconv('utf-8', 'gbk', $len_total);
			}
			$len_avg = floor($len_total / count($geos_parallel));
			$br = calc_geo_break($len_avg);
				$o = '';
				$o .= '<div class="geo_home_content">';
				$o .= '<blockquote>';
				$i = 0;
				foreach ($geos_parallel as $g => $g_name) {
					$i++;
					$css_color = rand_color();
					$o .= '<a href="/bbs/geo/' . $g . '" class="var" style="color: ' . $css_color . ';">' . $g_name . '</a>&nbsp; ';
					if ($i % $br == 0) {
						$o .= '<br />';
					}
				}
				$o .= '</blockquote>';
				$o .= '</div>';
				echo $o;
			}
		}
	public function nmGetRoute($geo = '') {
		if ($geo == '') {
			$geo = $this->geo->geo;
		}
		$route = array();
		$map = $this->map['path'][$geo];
		preg_match_all('/\//', $map, $seps);
		if (count($seps[0]) > 1) {
			$root = false;
		} else {
			$root = true;
		}
		if ($root) {
			//$route[$geo] = $this->map['name'][$geo];
			$route[$geo] = iconv('utf-8', 'gbk', $this->map['name'][$geo]);
		} else {
			$path = explode('/', substr($map, 1, strlen($map)));
			$i = 0;
			foreach ($path as $g) {
				$i++;
				if ($g != $geo) {
				//	$route[$g] = $this->map['name'][$g];
					$route[$g] = iconv('utf-8', 'gbk', $this->map['name'][$g]);
				}
			}
			//$route[$geo] = $this->map['name'][$geo];
			$route[$geo] = iconv('utf-8', 'gbk', $this->map['name'][$geo]);
		}
		return $route;
	}
}

/* E Geo class */

function geo_latest_update($geo) {
	global $db, $_DCACHE, $timestamp, $tablepre, $discuz_uid, $geos_all_children_sql;
	$data = array();
	$query = $db->query("SELECT t.subject, t.authorid,t.author,t.tid, t.lastpost, mf.uid, mf.avatar FROM {$tablepre}members m, {$tablepre}threads t LEFT JOIN {$tablepre}forums f ON f.fid=t.fid LEFT JOIN {$tablepre}memberfields mf ON mf.uid=t.authorid WHERE m.uid = t.authorid AND m.uid IN (SELECT uid FROM {$tablepre}members WHERE usr_geo IN ({$geos_all_children_sql})) ORDER BY t.lastpost DESC LIMIT 25");
	while($t = $db->fetch_array($query)) {
		$data['latest'][$t['tid']]['tid'] = $t['tid'];
		$data['latest'][$t['tid']]['subject'] = $t['subject'];
		$data['latest'][$t['tid']]['author'] = $t['author'] ? $t['author'] : '游客';
		$data['latest'][$t['tid']]['authorid'] = $t['authorid'];
		$data['latest'][$t['tid']]['avatar'] = avRESIZE($t['avatar'],'s');
	}
	$data['latest_expiration'] = 600 + time();
	if (mysql_num_rows($query) > 0) {
		nmwritetocache('geo_latest_'.$geo, '', nmgetcachevars($data),'',GEO_LATEST_DIR);
	}
	return $data['latest'];
}

function geo_hot_update($geo) {
	global $db, $_DCACHE, $timestamp, $tablepre, $discuz_uid, $geos_all_children_sql;
	$data = array();
	$now = getdate(time());
	$start = mktime(0, 0, 0, $now['mon'], 1, $now['year']);
	$query = $db->query("SELECT t.subject, t.authorid,t.author,t.tid,t.authorid,t.dateline,t.lastpost,t.views,t.replies FROM {$tablepre}threads t LEFT JOIN {$tablepre}forums f ON f.fid=t.fid WHERE t.authorid IN (SELECT uid FROM {$tablepre}members WHERE usr_geo IN ({$geos_all_children_sql})) AND t.dateline > {$start} ORDER BY t.views DESC,t.replies DESC LIMIT 10");
	while($t = $db->fetch_array($query)) {
		$data['hot'][$t['tid']]['tid'] = $t['tid'];
		$data['hot'][$t['tid']]['subject'] = $t['subject'];
		$data['hot'][$t['tid']]['views'] = $t['views'];
		$data['hot'][$t['tid']]['replies'] = $t['replies'];
	}
	$data['hot_expiration'] = 600 + time();
	if (mysql_num_rows($query) > 0) {
		nmwritetocache('geo_hot_'.$geo, '', nmgetcachevars($data),'',GEO_HOT_DIR);
	}
	return $data['hot'];
}

function geo_now_update($geo) {
	global $db, $_DCACHE, $timestamp, $tablepre, $discuz_uid, $geos_all_children_sql;
	$data = array();
	$query = $db->query("SELECT n.vid,n.dateline,n.author,n.authorid,n.content,n.background,mf.avatar FROM {$tablepre}plugin_now n LEFT JOIN {$tablepre}memberfields mf ON mf.uid=n.authorid
			WHERE n.authorid IN (SELECT uid FROM {$tablepre}members WHERE usr_geo IN ({$geos_all_children_sql})) ORDER BY dateline DESC LIMIT 10");
	while($n = $db->fetch_array($query)) {
		$data['now'][$n['vid']]['vid'] = $n['vid'];
		$data['now'][$n['vid']]['dateline'] = $nt['dateline'];
		$data['now'][$n['vid']]['author'] = $n['author'] ? $n['author'] : '游客';
		$data['now'][$n['vid']]['authorid'] = $n['authorid'];
		$data['now'][$n['vid']]['avatar'] = avRESIZE($n['avatar'],'s');
		$data['now'][$n['vid']]['content'] = $n['content'];
		$data['now'][$n['vid']]['background'] = nwFROM($n['background']);
	}
	$data['now_expiration'] = 600 + time();
	if (mysql_num_rows($query) > 0) {
		nmwritetocache('geo_now_'.$geo, '', nmgetcachevars($data),'',GEO_NOW_DIR);
	}
	return $data['now'];
}
?>
